package cn.com.haopy.dataes.es.utils;

import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class StockNumUtil {


    //public static String rootUrl = "http://localhost:8081/stockNum/";

    public static String rootUrl = "https://hos.hbyyy.com.cn:8081/stockNum/";


    /**
     * 先查询运费
     */
    public static String appId = "appId";

    public static String secret = "secret";

    /**
     * 进销存
     */
    public static String addNumUrl = rootUrl + "drug/addNum";


    /**
     * js转化为实体
     *
     * @param <T>
     * @param jsonstr
     * @param cls
     * @return
     */
    public static <T> T json2Obj(String jsonstr, Class<T> cls) {
        //JSONObject jo = JSONObject.parseObject(jsonstr);
        T obj = (T) JSONObject.parseObject(jsonstr, cls);
        return obj;
    }

    public static Map<String, Object> toMap(Object entity) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = entity.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true); // 使得私有字段也可以访问
            try {
                map.put(field.getName(), field.get(entity));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }


    /**
     * 判断字符串是否为空
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (s == null || "".equals(s.trim()))
            return true;
        return false;
    }

    public static String getValidatecode(int n) {
        Random random = new Random();
        String sRand = "";
        n = n == 0 ? 4 : n;// default 4
        for (int i = 0; i < n; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
        }
        return sRand;
    }

    public static Map<String, String> unionSign(Map<String, String> params, String appid, String secret) throws Exception {
        // TODO Auto-generated method stub
        params.remove("sign");
        if (isEmpty(secret)) {// 如果是md5则需要把md5的key加入到排序
            throw new Exception("appSecret 为空");
        }
        params.put("appid", appid);
        String random = getValidatecode(10);
        params.put("random", random);
        String time = new Date().getTime() + "";
        params.put("time", time);
        String signStr = "appid=" + appid + random + time + secret;

        params.put("sign", signStr);

        return params;
    }


}
